package cn.itcast.java.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Author itcast
 * Date 2021/10/13 6:54
 * Desc TODO
 */
public class ReflectDemo {
    public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        Class<Student> clazz = Student.class;
        Constructor ss = clazz.getDeclaredConstructor(String.class,int.class);
        Student zhangsan = (Student) ss.newInstance("zhangsan", 20);

        System.out.println(zhangsan);

        Field[] dfs = clazz.getDeclaredFields();
        for (Field df : dfs) {
            System.out.println(df);
        }

        Field name = clazz.getDeclaredField("name");
        Student student = clazz.newInstance();
        name.setAccessible(true);
        name.set(student,"wangwu");
        System.out.println(student.toString());

        Method  declaredMethods = clazz.getDeclaredMethod("show",String.class);
        declaredMethods.invoke(student,"beida");
    }

    private static class Student{
        private String name;
        private Integer age;

        public void show(String graduate){
            System.out.println("this is graduate :"+graduate +name);
        }

        public Student(){}

        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }

    }
}
